<template>
  <el-row :gutter="20">
    <el-col :span="6">
      <el-card>
        <template #header>
          <div class="card-header">
            <el-button
              size="mini"
              type="primary"
              class="button"
              icon="el-icon-plus"
              >新增
            </el-button>
            <el-button
              size="mini"
              type="success"
              class="button"
              icon="el-icon-edit"
              >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              class="button"
              icon="el-icon-delete"
            >
              删除
            </el-button>
          </div>
        </template>
        <el-input
          placeholder="请输入名称"
          @input="changeMenuName"
          @clear="tree.filter('')"
          v-model="menuName"
          clearable
          prefix-icon="el-icon-search"
        >
        </el-input>
        <el-tree
          class="tree-class"
          node-key="menuId"
          :expand-on-click-node="false"
          ref="tree"
          default-expand-all
          highlight-current
          @node-click="nodeClick"
          :data="menus"
          :filter-node-method="filterNode"
          :props="{
            children: 'children',
            label: 'menuName',
          }"
        >
        </el-tree>
      </el-card>
    </el-col>
    <el-col :span="18">
      <el-card></el-card>
    </el-col>
  </el-row>
</template>

<script>
import { getMenuListApi } from '@/api/system.api';
import { reactive, toRefs, getCurrentInstance, onMounted } from 'vue';
import { listToMenu, debounce } from '@/utils/tools';
export default {
	setup () {
		let Instance = getCurrentInstance().proxy;
		let tree = null;
		let state = reactive({
			menuName : '',
			menus : []
		});

		let nodeClick = (params) => {
			console.log(params);
		};

		let changeMenuName = debounce((val) => {
			tree.filter(val);
		}, 300);

		onMounted(() => {
			tree = Instance.$refs['tree'];
		});

		let filterNode = (value, payload) => {
			if (!value) return true;
			return payload.menuName.indexOf(value) !== -1;
		};

		/**
     * 菜单处理，
     * 按钮不展示的菜单里面
     */

		let dataAdaptive = (menus) => {
			menus.forEach((item) => {
				if (
					(item.menuType === 'M' || item.menuType === 'C') &&
          Array.isArray(item.children)
				) {
					if (item.children[0] && item.children[0].menuType === 'F') {
						item.buttonGroup = item.children;
						delete item.children;
					} else {
						dataAdaptive(item.children);
					}
				}
			});
			return menus;
		};

		let init = async () => {
			let res = await getMenuListApi();
			state.menus = dataAdaptive(
				listToMenu({ list : res.list, idKey : 'menuId' })
			);
			console.log(state.menus);
		};

		init();

		return {
			...toRefs(state),
			filterNode,
			changeMenuName,
			nodeClick
		};
	}
};
</script>

<style lang="scss" scoped></style>
